package com.avicsafety.ezsystem.pdf;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.avicsafety.ezsystem.R;
import com.avicsafety.ezsystem.utils.SDCardUtils;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.CMYKColor;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class PdfActivity extends AppCompatActivity {


    private static final String TAG = "PdfActivity";
    private static final String PDF_PATH = SDCardUtils.getSDCardPath()+"temp/test.pdf";
    private static final String PDF_DEMOPATH = SDCardUtils.getSDCardPath()+"temp/demo.pdf";
    private static final String CONTEXT = "Hello iText \n 这里是中文..字号16 字体仿宋.";
    public static final String FONTDIR = SDCardUtils.getSDCardPath()+"Fonts";
    private static final String FONT_HWZS = FONTDIR+"/hwzs.ttf";
    private static final String FONT_SIMFANG = FONTDIR+"/simfang.ttf";
    private static final String FONT_WINGDING = FONTDIR+"/Wingdings2.ttf";
    private static final String SIGN_PATH = SDCardUtils.getSDCardPath()+"temp/sign.png";

    public static final String CHINESE = "\u5341\u950a\u57cb\u4f0f";
    private static final String IMG_PATH = SDCardUtils.getSDCardPath()+"temp/zzz.png";

    private Button button_create_cn;
    private Button button_read;
    private Button button_draw_line;
    private Button button_pdf_view;
    private Button button_hand_write;
    private Button button_test;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);

        mContext = this;

        button_create_cn = findViewById(R.id.button_create_cn);
        button_create_cn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                createPdfCn();
                //sharePdf();
                openFile(PDF_PATH);
            }
        });

        button_read = findViewById(R.id.button_read);
        button_read.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                readPdf();
                //sharePdf();
                openFile(PDF_PATH);
            }
        });

        button_draw_line = findViewById(R.id.button_draw_line);
        button_draw_line.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                drawLine();
                //sharePdf();
                openFile(PDF_PATH);
            }
        });

        button_pdf_view = findViewById(R.id.button_pdf_view);
        button_pdf_view.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext,PdfViewActivity.class));
            }
        });

        button_hand_write = findViewById(R.id.button_hand_write);
        button_hand_write.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(mContext,HandWriteActivity.class),200);
            }
        });

        button_test = findViewById(R.id.button_test);
        button_test.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                test();
            }
        });


    }

    private void test() {

        //实例化 传入上下文 和 每行文字数  默认值为76
        PdfManager pdfManager = new PdfManager(mContext,76);
        pdfManager.setShowLine(true);
        //指定第一页模板
        pdfManager.setTemplate(R.raw.ajysspb_pdf);
        //指定附页模板
        pdfManager.setTemplate2(R.raw.attachment_pdf);

        //正文由 block 组成
        String _con = "东晋十六国期间，柔然与乌孙国因土地问题开始漫长的战斗，然而乌孙国的军资和战力是远不及有丰富战斗经验的柔然人的。国人为了逃离战争的苦楚和柔然的苦苦相逼只能一路向南迁徙，以游牧方式作为乌孙人的基础生活。也被称为哈萨克人。东晋十六国期间，柔然与乌孙国因土地问题开始漫长的战斗，然而乌孙国的军资和战力是远不及有丰富战斗经验的柔然人的。国人为了逃离战争的苦楚和柔然的苦苦相逼只能一路向南迁徙，以游牧方式作为乌孙人的基础生活。也被称为哈萨克人。东晋十六国期间，柔然与乌孙国因土地问题开始漫长的战斗，然而乌孙国的军资和战力是远不及有丰富战斗经验的柔然人的。国人为了逃离战争的苦楚和柔然的苦苦相逼只能一路向南迁徙，以游牧方式作为乌孙人的基础生活。也被称为哈萨克人。";
        Set<Block> blocks = new HashSet<>();
        blocks.add(new Block("简单正文",170f,646f));
        blocks.add(new Block(_con,170f,535.5f, Block.FONT_CODE_CONTENT,4, 0, 58*2, true,"(接续页xx)",58));
        blocks.add(new Block(_con,170f,335.5f, Block.FONT_CODE_CONTENT,4, 0, 58*2, true,"(接续页xx)",58));
        blocks.add(new Block("第三个小正文",170f,446f));

        pdfManager.setContext(blocks);
        try {
            String filePath = SDCardUtils.getSDCardPath()+File.separator+"temp"+ File.separator+"test.pdf";
            pdfManager.makeDocFile(SDCardUtils.getSDCardPath()+File.separator+"temp","test.pdf");
            openFile(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (requestCode == 200) {
            if (resultCode == RESULT_OK) {
                sign();
                openFile(PDF_PATH);
            }
        }
    }

    private void sign(){
        try {

            FontFactory.register(FONT_HWZS,"hwzs");
            Font hwzs = FontFactory.getFont("hwzs", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 16, Font.NORMAL);
            Font hwzs_line = FontFactory.getFont("hwzs", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 16, Font.UNDERLINE);


            PdfReader template = new PdfReader(PDF_DEMOPATH); //读取pdf 这个是底板
            PdfStamper stamper = new PdfStamper(template, new FileOutputStream(PDF_PATH));

            PdfContentByte over = stamper.getOverContent(1);

            //插入印章 这里也可以替换成签名
            Image img = Image.getInstance(SIGN_PATH);
            //图像 宽度 u u 高度 x y
            over.addImage(img, 80, 0, 0, 40, 280, 210);
            //over.restoreState();


            stamper.close();

            template.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在已经已经存在PDF上画线
     */
    private void drawLine() {

        PdfReader template = null; //读取pdf 这个是底板
        PdfStamper stamper = null;
        try {
            template = new PdfReader(PDF_DEMOPATH);
            stamper = new PdfStamper(template, new FileOutputStream(PDF_PATH));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        PdfContentByte over = stamper.getOverContent(1);

        CMYKColor magentaColor = new CMYKColor(0.f, 1.f, 0.f, 0.f);
        over.setColorStroke(magentaColor);
        over.moveTo(36, 36);
        over.lineTo(36, 806);
        over.lineTo(559, 36);
        over.lineTo(559, 806);
        over.closePathStroke();

        try {
            stamper.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        template.close();


    }

    /**
     * 读取一个pdf
     */
    private void readPdf() {
        try {

            FontFactory.register(FONT_HWZS,"hwzs");
            Font hwzs = FontFactory.getFont("hwzs", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 16, Font.NORMAL);
            Font hwzs_line = FontFactory.getFont("hwzs", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 16, Font.UNDERLINE);


            PdfReader template = new PdfReader(PDF_DEMOPATH); //读取pdf 这个是底板
            PdfStamper stamper = new PdfStamper(template, new FileOutputStream(PDF_PATH));

            PdfContentByte over = stamper.getOverContent(1);


            //画一个矩形
            Rectangle rect = new Rectangle(100,100);
            rect.setBorder(Rectangle.BOX);
            rect.setBorderWidth(0.5f);
            rect.setBorderColor(BaseColor.RED);
            //PdfContentByte cb = writer.getDirectContent();


            Phrase p = new Phrase();
            p.add(new Chunk("前",hwzs_line));
            p.add(new Chunk("前",hwzs));
            p.add(new Chunk("中",hwzs));
            p.add(new Chunk("后",hwzs));


            ColumnText.showTextAligned(over, Element.ALIGN_LEFT, p, 80, 650, 0);
//            ColumnText.showTextAligned(over, Element.ALIGN_LEFT,
//                    new Paragraph("多个地方/n111\n阿斯顿发达省份",hwzs),
//                     34,122, 0);

            //ColumnText.fitText(hwzs,"打法是否\n大师法师打发斯蒂芬",rect,16,1);

            //over.saveState();

//            Document document = new Document();
//            Document document = canvas.getPdfDocument();
//            canvas.addTemplate(new PdfTemplate());
//            document.open();
//
//            Chapter chapter = new Chapter(new Paragraph("Hello \n 第二行 \n 3333....",hwzs), 1);
//            document.add(chapter); //插入chapter
//            document.close();


//            canvas.getPdfDocument();
//            canvas.beginText();
//            canvas.setFontAndSize(hwzs.getBaseFont(),16);
//            canvas.setTextMatrix(80,675);
//
//            canvas.showText("Insert into Text 插入的文本\n 第二行文本 " );
//
//            canvas.endText();

            //over.rectangle(rect);


            //透明度
//            PdfGState gs1 = new PdfGState();
//            gs1.setFillOpacity(0.5f);
//            over.saveState();
//            over.setGState(gs1);


            //插入印章 这里也可以替换成签名
            Image img = Image.getInstance(IMG_PATH);
            //图像 宽度 u u 高度 x y
            over.addImage(img, 100, 0, 0, 100, 400, 200);
            //over.restoreState();


            stamper.close();

//            Document document = new Document(); //新建
//            PdfCopy copy = new PdfCopy(document, new FileOutputStream(PDF_PATH)); //新建copy
//            document.open();
//            copy.addDocument(template); //拷贝模板文档 到新pdf
//            Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.BOLDITALIC);
//            Chapter chapter = new Chapter(new Paragraph("Hello",chapterFont), 1);
//            document.add(chapter); //插入chapter

            template.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成PDF中文文档
     */
    private void createPdfCn() {
        Log.e(TAG,PDF_PATH);
        File file = new File(PDF_PATH);
        file.getParentFile().mkdirs();
        try {
            createPdf(PDF_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void createPdf(String dest) throws IOException, DocumentException {


//        Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张
//        Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距

        // 使用微软雅黑字体显示中文
        // String yaHeiFontName = getResources().getString(R.raw.msyhl);

        //字体处理
        Log.e(TAG,FONT_SIMFANG);
        FontFactory.register(FONT_SIMFANG,"simfang");
        FontFactory.register(FONT_HWZS,"hwzs");
        FontFactory.register(FONT_WINGDING,"wingding");


        Font simfang = null;
        Font hwzs = null;
        Font wingding = null;

        try {
            simfang = FontFactory.getFont("simfang", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            simfang.setSize(16);
            hwzs = FontFactory.getFont("hwzs", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            hwzs.setSize(12);
            wingding = FontFactory.getFont("wingding", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            wingding.setSize(20);
        }
        catch(Exception e) {
            Log.e(TAG,"error : FONT CREATE FIAL");
            return;
        }

        //插入文字
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
//        Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, Font.BOLDITALIC);
//        Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
        Chunk chunk = new Chunk(String.format("CHINESE: %s", CONTEXT), simfang);
        //Chunk chunk = new Chunk(String.format("CHINESE: %s", CHINESE), font);

        Paragraph title = new Paragraph("我是标题",hwzs);
        title.setAlignment(1); //居中

        Chapter chapter = new Chapter(new Paragraph(chunk), 1);
        chapter.setNumberDepth(0);

        chapter.add(title);

        chapter.add(new Paragraph("华文中宋以及乱码配合演示 :字号12 这里要换行,.了 \n", hwzs));
        Chunk chunk1 = new Chunk("这里是开始", simfang);
        Chunk chunk2 = new Chunk("23456", wingding);
        Chunk chunk3 = new Chunk("尾巴", simfang);
        chapter.add(chunk1);
        chapter.add(chunk2);
        chapter.add(chunk3);
        chapter.add(new Paragraph("这里是开始 :", hwzs));
        chapter.add(new Paragraph("123456789abcqewrtyuiopa;ldsfkjghjzcxmvnb", wingding));
        chapter.add(new Paragraph("这里是结尾 :", hwzs));
        document.add(chapter);
        document.close();

        Log.e(TAG,"created");
    }

    public void sharePdf(){
        File file = new File(PDF_PATH);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.addCategory("android.intent.category.DEFAULT");
        Uri pdfUri;
//        pdfUri = Uri.fromFile(file);
        if (Build.VERSION.SDK_INT >= 24) {
            pdfUri = FileProvider.getUriForFile(mContext, "com.avicsafety.ezsystem", file);
        } else {
            pdfUri = Uri.fromFile(file);
        }
        intent.putExtra(Intent.EXTRA_STREAM, pdfUri);
        intent.setType("application/pdf");

        try {
            mContext.startActivity(Intent.createChooser(intent, file.getName()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openFile(String path){
        File file = new File(path);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //data是file类型,忘了复制过来
            uri = FileProvider.getUriForFile(mContext, "com.avicsafety.ezsystem", file);
        } else {
            uri=Uri.fromFile(file);
        }
        //pdf文件要被读取所以加入读取权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "application/pdf");
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);

            if (chr1 >= 1621 && chr1 <= 177745) {// 汉字范围 \u0391-\uFFE5
                // (中文)加全角字符（16-8）
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }
}
